import type { ObjectLiteral } from 'typeorm';
import { SelectQueryBuilder } from 'typeorm';
import type { QueryParams, PaginationResult } from 'src/types';

/**
 * 为查询构造器设置分页功能。
 * @async
 * @template T 泛型类型，继承自 ObjectLiteral。
 * @param {SelectQueryBuilder<T>} queryBuilder 查询构造器实例。
 * @param {QueryParams} paginationQueryParams 分页查询参数。
 * @param {((records: T[]) => T[])?} [callback] 可选的回调函数，用于处理记录数据。
 * @returns {Promise<PaginationResult>} 包含当前页、总页数、总数和记录数据的分页信息对象。
 */
export const setQueryBuilderPagination = async <T extends ObjectLiteral>(
  queryBuilder: SelectQueryBuilder<T>,
  paginationQueryParams: QueryParams,
  queryTableName: string,
  callback?: (records: Record<string, any>[]) => Record<string, any>[],
): Promise<PaginationResult> => {
  const { pageSize, currentPage } = paginationQueryParams;
  queryBuilder.take(pageSize).skip((currentPage - 1) * pageSize);

  const [recordsRaw, total] = await queryBuilder.getManyAndCount();

  const records = callback ? callback(recordsRaw) : recordsRaw;

  return {
    currentPage: Number(currentPage),
    totalPages: Math.ceil(total / pageSize),
    total: Number(total),
    pageSize: Number(pageSize),
    list: records,
  };
};
